import LayoutWhite from "@/components/LayoutWhite";
import Title from "@/components/Title";
import Titles from "@/components/Titles";
import OSS from "ali-oss";
import { Button, Col, DatePicker, Form, Input, message, Row, Select, Upload } from "antd";
import { useEffect, useState } from "react";
import { useTabsContext } from "@/contexts/TabsContext";
import { addHisList } from "@/api/modules/jilu";
import { yuangongList } from "@/api/modules/yuangong";

const shopCar = () => {
	// "id":"LTAI5tBAudw6nSw3jcMJHGXd",
	// "key":"rAXR0pdiEyD4C48dRsOAKrDPBsGqLO",
	// "bucket":"uaipeizhen",
	// "endPoint":"oss-cn-hangzhou.aliyuncs.com"

	const [formVal, setFormVal] = useState<any>({});
	const [userLen, setUserLen] = useState<number>(1);
	const [userLen1, setUserLen1] = useState<number>(1);
	const [fileList, setFileList] = useState<any[]>([]);
	const [fileList1, setFileList1] = useState<any[]>([]);
	const [fileList2, setFileList2] = useState<any[]>([]);
	const [client, setClient] = useState<any>(null);
	const [progess, setProgess] = useState<number>(0);
	const [videoList, setVideoList] = useState<any[]>([]);
	const [isCheck, setIsCheck] = useState<boolean>(false);

	const [pzData, setPz] = useState<any[]>([]);

	useEffect(() => {
		const client = new OSS({
			// yourRegion填写Bucket所在地域。以华东1（杭州）为例，Region填写为oss-cn-hangzhou。
			region: "oss-cn-hangzhou",
			// // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
			// accessKeyId: "LTAI5tJDQtwoo2Kr3C56zPRs",
			// accessKeySecret: "1eI3f17rGKTh5WmRgIXUyQU2xVD2eo",
			// bucket: "yunhao"
			// endpoint: "oss-cn-hangzhou.aliyuncs.com"
			accessKeyId: "LTAI5tBAudw6nSw3jcMJHGXd",
			accessKeySecret: "rAXR0pdiEyD4C48dRsOAKrDPBsGqLO",
			bucket: "uaipeizhen"
			// endPoint: "oss-cn-hangzhou.aliyuncs.com"
		});
		setClient(client);
	}, []);

	const beforeUpload = async (file: any, key: string) => {
		const result = await client.put(file.name, file);
		if (key === "fileList") {
			setFileList([
				...fileList,
				{
					url: result.url,
					uid: result.url
				}
			]);
		} else if (key === "fileList1") {
			setFileList1([
				...fileList1,
				{
					url: result.url,
					uid: result.url
				}
			]);
		} else if (key === "fileList2") {
			setFileList2([
				...fileList2,
				{
					url: result.url,
					uid: result.url
				}
			]);
		}
	};

	const handleUpload = async (file: any) => {
		setIsCheck(true);
		const result = await client.multipartUpload(file.name, file, {
			partSize: 1024 * 1024 * 5,
			progress: (p: any) => {
				const percentage = Math.floor(p * 100);
				setProgess(percentage);
				console.log(progess, percentage);
			}
		});
		setIsCheck(false);
		setProgess(0);
		setVideoList([
			{
				url: result.res.requestUrls[0].split("?")[0],
				uid: result.res.requestUrls[0].split("?")[0],
				name: result.name,
				status: "done"
			}
		]);
	};

	console.log(setFileList);
	console.log(formVal);
	const { delTabs } = useTabsContext();
	console.log(delTabs);
	const [from] = Form.useForm();
	const onFinish = async (values: any) => {
		const grouped: any = {};
		for (const key in values) {
			if (key.includes("drugOne") || key.includes("drugTwo") || key.includes("drugThree")) {
				const suffix = key.slice(-1);
				if (!grouped[suffix]) {
					grouped[suffix] = {};
				}
				grouped[suffix][key.includes("drugOne") ? "one" : key.includes("drugTwo") ? "two" : "three"] = values[key];
			}
		}

		const grouped1: any = {};
		for (const key in values) {
			if (key.includes("monmeyOne") || key.includes("monmeyTwo")) {
				const suffix = key.slice(-1);
				if (!grouped1[suffix]) {
					grouped1[suffix] = {};
				}
				grouped1[suffix][key.includes("monmeyOne") ? "one" : "two"] = values[key];
			}
		}

		const result = Object.values(grouped);
		const result1 = Object.values(grouped1);

		const req = {
			...values,
			audioUrl: videoList?.[0].url,
			doctorsAdvice: JSON.stringify({
				one: fileList,
				two: fileList1,
				three: fileList2
			}),
			doctorsAdviceImg: JSON.stringify({
				one: result,
				two: result1
			})
		};
		await addHisList(req);
		// message.success(JSON.stringify(values));
		setFormVal(values);
		// delTabs("/staff/adds");
	};

	const goBack = () => {
		delTabs("/staff/adds");
	};

	// 拓展按钮 可传可不传
	const moreButton = () => {
		return "";
	};

	const submit = () => {
		from.submit();
	};

	// const timer = async () => {
	// 	return new Promise(resolve => {
	// 		setTimeout(() => {
	// 			resolve({
	// 				uid: Math.floor(Math.random() * 10),
	// 				name: "image.png",
	// 				status: "done",
	// 				url: "https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png"
	// 			});
	// 		}, 1000);
	// 	});
	// };

	const getPz = async () => {
		const {
			data: { data }
		} = await yuangongList({});
		setPz(
			data?.map((item: any) => {
				return {
					label: item.name,
					value: item.code
				};
			})
		);
	};

	useEffect(() => {
		getPz();
	}, []);

	return (
		<LayoutWhite>
			<Title word={"新增陪诊记录"} more={moreButton()} />
			<Form
				name="basic"
				form={from}
				labelCol={{ span: 8 }}
				wrapperCol={{ span: 8 }}
				style={{ width: "100%", padding: "20px 0px" }}
				initialValues={{ remember: true }}
				onFinish={onFinish}
				onFinishFailed={() => message.info("请输入必填项")}
				autoComplete="off"
			>
				<Titles title={"基本信息"} />
				<Form.Item label="陪诊时间" name="escortTime" rules={[{ required: true, message: "请选择陪诊时间" }]}>
					<DatePicker placeholder="请选择陪诊时间" allowClear format="YYYY-MM-DD" />
				</Form.Item>

				<Form.Item label="就诊医院" name="hospital" rules={[{ required: true, message: "请输入就诊医院" }]}>
					<Input placeholder="请输入就诊医院" />
				</Form.Item>

				<Form.Item label="就诊科室" name="department" rules={[{ required: true, message: "请输入就诊科室" }]}>
					<Input placeholder="请输入就诊科室" />
				</Form.Item>

				<Form.Item label="就诊医生" name="doctor" rules={[{ required: true, message: "请输入就诊医生" }]}>
					<Input placeholder="请输入就诊医生" />
				</Form.Item>

				<Form.Item label="陪诊人员" name="accPerCode" rules={[{ required: true, message: "请选择陪诊人员" }]}>
					<Select placeholder="请选择陪诊人员" options={pzData}></Select>
				</Form.Item>

				<Titles title={"诊断过程"} />
				<Form.Item label="视频上传" name="video">
					{progess !== 0 && <span>视频上传中 进度为{progess}% 请勿退出本页面！</span>}
					{videoList?.length > 0 ? (
						<video src={videoList[0]?.url} controls style={{ width: "350px", height: "250px" }} />
					) : (
						<Upload
							name="file"
							listType="picture-card"
							className="avatar-uploader"
							fileList={videoList}
							disabled={isCheck}
							showUploadList={false}
							customRequest={({ file }) => handleUpload(file)}
						>
							视频上传
						</Upload>
					)}
				</Form.Item>

				<Titles title={"注意事项"} />
				<Form.Item label="注意事项" name="description">
					<Input.TextArea placeholder="请输入注意事项" style={{ height: "80px" }} />
				</Form.Item>

				<Titles title={"用药医嘱"} />
				{new Array(userLen).fill("").map((_: any, ind: number, arr: any) => {
					return (
						<Row key={ind} gutter={24}>
							<Col span={6}></Col>
							<Col span={6}>
								<Form.Item wrapperCol={4} label={`用药${ind + 1}`} name={`drugOne${ind + 1}`}>
									<Input />
								</Form.Item>
							</Col>
							<Col span={5}>
								<Form.Item wrapperCol={4} label={``} name={`drugTwo${ind + 1}`}>
									<Input />
								</Form.Item>
							</Col>
							<Col span={4}>
								<Form.Item wrapperCol={4} label={``} name={`drugThree${ind + 1}`}>
									<Input />
								</Form.Item>
							</Col>
							{ind !== arr.length - 1 && <Button onClick={() => setUserLen(userLen - 1)}>删除本行</Button>}
							{ind === arr.length - 1 && <Button onClick={() => setUserLen(userLen + 1)}>新增一行</Button>}
						</Row>
					);
				})}
				<Form.Item label="凭证上传(多)" name="1">
					<Upload
						listType="picture-card"
						fileList={fileList}
						onRemove={e => {
							const newList = JSON.parse(JSON.stringify(fileList));
							const index = fileList.findIndex(item => item.uid === e.uid);
							newList.splice(index, 1);
							setFileList(newList);
						}}
						onPreview={() => {
							debugger;
						}}
						beforeUpload={e => beforeUpload(e, "fileList")}
					>
						1
					</Upload>
				</Form.Item>

				<Titles title={"检查报告"} />
				<Form.Item label="检查报告(多)" name="2">
					<Upload
						listType="picture-card"
						fileList={fileList1}
						onRemove={e => {
							const newList = JSON.parse(JSON.stringify(fileList1));
							const index = fileList1.findIndex(item => item.uid === e.uid);
							newList.splice(index, 1);
							setFileList1(newList);
						}}
						beforeUpload={e => beforeUpload(e, "fileList1")}
					>
						1
					</Upload>
				</Form.Item>

				<Titles title={"复查建议"} />
				<Form.Item label="复查建议" name="reviewInfo" rules={[{ required: true, message: "请选择上传视频" }]}>
					<Input placeholder="请输入复查建议" />
				</Form.Item>
				<Form.Item label="复查时间" name="reviewDate" rules={[{ required: true, message: "请选择陪诊时间" }]}>
					<DatePicker placeholder="请选择陪诊时间" allowClear format="YYYY-MM-DD" />
				</Form.Item>

				<Titles title={"本次花费"} />
				{new Array(userLen1).fill("").map((_: any, ind: number, arr: any) => {
					return (
						<Row key={ind} gutter={18}>
							<Col span={6}></Col>
							<Col span={6}>
								<Form.Item wrapperCol={6} label={`花费${ind + 1}`} name={`monmeyOne${ind + 1}`}>
									<Input />
								</Form.Item>
							</Col>
							<Col span={4}>
								<Form.Item wrapperCol={4} label={``} name={`monmeyTwo${ind + 1}`}>
									<Input />
								</Form.Item>
							</Col>
							{ind !== arr.length - 1 && <Button onClick={() => setUserLen1(userLen1 - 1)}>删除本行</Button>}
							{ind === arr.length - 1 && <Button onClick={() => setUserLen1(userLen1 + 1)}>新增一行</Button>}
						</Row>
					);
				})}
				<Form.Item label="凭证上传(多)" name="3">
					<Upload
						listType="picture-card"
						fileList={fileList2}
						onRemove={e => {
							const newList = JSON.parse(JSON.stringify(fileList2));
							const index = fileList2.findIndex(item => item.uid === e.uid);
							newList.splice(index, 1);
							setFileList2(newList);
						}}
						beforeUpload={e => beforeUpload(e, "fileList2")}
					>
						1
					</Upload>
				</Form.Item>
			</Form>
			<Title word={""} more={moreButton()} />
			<div style={{ display: "flex", justifyContent: "center", alignItems: "center" }}>
				<Button style={{ marginRight: "30px" }} onClick={() => goBack()}>
					返回
				</Button>
				<Button type="primary" onClick={() => submit()}>
					确认保存
				</Button>
			</div>
		</LayoutWhite>
	);
};

export default shopCar;
